var textSmileys = new Array(":)", ":(", ":wink:", ":p", ":lol:", ":mad:",
			":heartbeat:", ":love:", ":eprop:", ":wave:", ":sunny:", ":wha:",
			":yes:", ":sleepy:", ":rolleyes:", ":lookaround:", ":eek:",
			":confused_2:", ":nono:", ":fun:", ":goodjob:", ":giggle:",
			":cry:", ":shysmile:", ":jealous:", ":whocares:", ":spinning:",
			":coolman:", ":littlekiss:", ":laugh:");

	var realSmileys = new Array("images/smileys/smiley1.gif",
			"images/smileys/smiley2.gif",
			"images/smileys/AliceSmileyAnimatedWink.gif",
			"images/smileys/smiley4.gif",
			"images/smileys/Smileylol.gif",
			"images/smileys/7_mad.gif",
			"images/smileys/heartbeating.gif",
			"images/smileys/SmileLove.gif",
			"images/smileys/eProp.gif",
			"images/smileys/SmileyWave.gif",
			"images/smileys/sunnySmiley.gif",
			"images/smileys/wha.gif",
			"images/smileys/yes.gif",
			"images/smileys/Smileysleep.gif",
			"images/smileys/Smileyrolleyes.gif",
			"images/smileys/SmileyLookaround.gif",
			"images/smileys/Smileyeek.gif",
			"images/smileys/Smileyconfused.gif",
			"images/smileys/SmileyAnimatedNoNo.gif",
			"images/smileys/propeller.gif",
			"images/smileys/goodjob.gif",
			"images/smileys/emot-giggle.gif",
			"images/smileys/blueAnimatedCry.gif",
			"images/smileys/Animatedshysmile.gif",
			"images/smileys/AliceJealous.gif",
			"images/smileys/19_indifferent.gif",
			"images/smileys/Smileyspinning.gif",
			"images/smileys/25_coolguy.gif",
			"images/smileys/AliceSmileyAnimatedBlinkKiss.gif",
			"images/smileys/LaughingAgua.gif");

function replaceSmiley(message)

{

	

	var preloadedImages = new Array(realSmileys.length);
	for (i = 0; i < preloadedImages.length; ++i) {
		preloadedImages[i] = new Image();
		preloadedImages[i].src = realSmileys[i];
	}

	for ( var n = 0; n < textSmileys.length; ++n) {
		while (message.indexOf(textSmileys[n]) != -1) {
			smiley = '<img src=\"' + realSmileys[n] + '">'
			message = message.replace(textSmileys[n], smiley);
		}
	}
	return message
}

function randomNumber() {
	return Math.random() * 10000;
}

function populateSmileysTable(textareaid){
	imageTable = document.getElementById('smileyTable')
	count =0
	rows = imageTable.getElementsByTagName('tr');
	rowsLength = rows.length
	for (i=0;i<rowsLength ;i++) {
		imageTable.deleteRow((4-rowsLength));
	}
	rows = imageTable.getElementsByTagName('tr');
	for (i=0;i<5 ;i++ )
	{
		currRow = imageTable.insertRow(i);
		for (j=0;j<6 ;j++ )
		{
			currCell = currRow.insertCell(j);
			currCell.innerHTML ="<img style='cursor=hand' src='"+realSmileys[count]+"' onclick=selectedSmiley('"+textSmileys[count]+"','"+textareaid+"') /><br/>"+textSmileys[count]
			currCell.align='center'
			count++
		}
	}
	
}
function selectedSmiley(value,textareaid){
	document.getElementById(textareaid).value = document.getElementById(textareaid).value + value
	dijit.byId('smileys').hide()
	document.getElementById(textareaid).focus()
	
}


function getImageName(Status) {
	var image = '';
	if (Status == 'A_AVAILABLE') {
		image = 'Available_S_NON'
	} else if (Status == 'B_BUSY') {
		image = 'Busy_S_NON'
	} else if (Status == 'C_AWAY') {
		image = 'Away_S_NON'
	} else if (Status == 'D_LOGOUT') {
		image = 'Logout_S_NON'
	}
	return image
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function getDisplayName(loginId) {
	for ( var i_tem = 0; i_tem < currentOnlineUsers.length; i_tem++) {
		if (currentOnlineUsers[i_tem][0] == loginId)
			return currentOnlineUsers[i_tem][2]
	}
}

function getImagePath(loginId) {
	for ( var i_tem = 0; i_tem < currentOnlineUsers.length; i_tem++) {
		if (currentOnlineUsers[i_tem][0] == loginId)
			return currentOnlineUsers[i_tem][3]
	}
}
/*function setTimerFunctions() {
	if (enableAutoRefresh) {
		var t1 = setTimeout("getOnline{UsersFrmServer()", onlineUserTimeout);
		var t2 = setTimeout("receiveMessagesFrmServer()", messageRefreshTimeout);
	}
}*/

function keypressed() {
	if (event.keyCode == '13') {
		if (selectedLoginId != null && selectedLoginId != '') {
			sendMessage(selectedLoginId)
		}
	}
}

function scrollToTop(userid) {
	chatDiv = document.getElementById(userid + '_chathistory')
	chatDiv.scrollTop = chatDiv.scrollHeight;
}
function changeTimeouts(noOfMessages, reqType) {
	if (reqType == 'RECEIVE'){
		if (noOfMessages > 0) {
			messageRefreshTimeout = messageRefreshTimeoutMinThresold
		} else {
			if ((messageRefreshTimeout + 1000) < messageRefreshTimeoutMaxThresold) {
				messageRefreshTimeout = messageRefreshTimeout + 1000
			}

		}
	} else {
		messageRefreshTimeout = messageRefreshTimeoutMinThresold
	}
	
}
function changeTitle(title) {
	var oldTitle = document.title;
	var msg = title;
	var timeoutId = setInterval(function() {
		document.title = document.title == msg ? oldTitle : msg;
	}, 1000);
	document.onmousemove = function() {
		clearInterval(timeoutId);
		document.title = oldTitle;
		document.onmousemove = null;
	};
	return timeoutId;
}

function createFriendRequestToolTips(loginId) {
	new dijit.Tooltip({
	     connectId: ["yesbt_"+loginId],
	     label: "Approve "+ loginId +"'s friend Request"
	  });
	new dijit.Tooltip({
	     connectId: ["nobt_"+loginId],
	     label: "Reject "+loginId+"'s friend Request"
	  });
}

function createWaitingFriendRequestToolTips(loginId) {
	new dijit.Tooltip({
	     connectId: ["waitbt_"+loginId],
	     label:  loginId +" has not approved your friend Request"
	  });
}

function getDisplayNameFrmUserId(userid){
	for (i=0;i<currentOnlineUsers.length;i++){
		if (userid==currentOnlineUsers[i][0]){
			return currentOnlineUsers[i][2]
		}
	}
		
}

function getSmallImageValue(mediumImageValue){
	return mediumImageValue.replace('_m','_s')
}

function getMessageTime(messageDateText){
		messageDate = new Date(messageDateText)
		currentDate = new Date()
		timeDiff = Math.floor((currentDate-messageDate)/(60*60*1000))
		dayDiff = Math.floor((currentDate-messageDate)/(60*60*1000*24))
		minuteDiff =  Math.floor((currentDate-messageDate)/(60*1000))
		if (dayDiff > 0)
		{
			result = dayDiff + ( dayDiff > 1? " Days ago":" Day ago")
		} else if (timeDiff >= 1 && timeDiff <= 24)
		{
			result = timeDiff +( timeDiff > 1? " Hrs ago":" Hr ago")
		} else if (minuteDiff >= 1){
			result = minuteDiff +( minuteDiff > 1? " Mins ago":" Min ago")
		} else {
			result = 'less than a minute ago'
		}
		return result;
}

function getCurrentTime(){
	return dateFormat(new Date(), "mmm dd, yyyy HH:MM:ss")
}
function updateMessageTime(userId){
	messageTimeId = userId+'_messageTime'
	messagesTime = document.getElementsByName(messageTimeId)
	for ( var i_tem = 0; i_tem < messagesTime.length; i_tem++) {
		arr = messagesTime[i_tem].value.split('#')
		document.getElementById('displayTime_'+arr[0]).innerHTML = getMessageTime(arr[1])
	}
}
Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
	if (this[i] == element) {
	return true;
	}
	}
	return false;
	}
function removeByElement(arrayName,arrayElement)
{
 for(var i=0; i<arrayName.length;i++ )
  { 
 if(arrayName[i]==arrayElement)
 arrayName.splice(i,1); 
 } 
 }

function changeStyle(ele, newstyle)
{
	ele.className = newstyle
}

function truncateString(value, number){
	temp = value.indexOf(' ')
	if ((value.length>= (2*number)) && ((temp > number && temp < number/2) ||temp==-1)){
		return value.substring(0,(number-5)) + "..."
	} else {
		return value
	}
}
function getValueFrmReqParams(reqURL, paramName){
	indexOfParam = reqURL.indexOf(paramName)
	if (indexOfParam != -1)
	{
		return reqURL.substring(indexOfParam+paramName.length+1,reqURL.length)
	}
}

function validateEmail(value) {
	var error=false;
	var tfld = trim(value); // value of field with whitespace trimmed off
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

	if (value == "Enter your email Address") {

		error = true;
	} else if (!emailFilter.test(tfld)) { //test email for illegal characters

		error = true;
	} else if (value.match(illegalChars)) {

		error = true;
	}
	return error;
}

function trim(s)
{
	return s.replace(/^\s+|\s+$/, '');
}

function resetSessionTimers(){
	// if already timer is set
	// first clear it
	if (userAwayTimeoutId != null && userSessionExpireTimeoutId != null){
		clearInterval(userAwayTimeoutId);
		clearInterval(userSessionExpireTimeoutId);
	}
	userAwayTimeoutId = setTimeout("changeUserStatusAway()",userAwayTimeout);
	userSessionExpireTimeoutId = setTimeout("logoutUser()",sessionTimeout);
	
	// Change status to available
	changeStatus('A_AVAILABLE')
}

function changeUserStatusAway(){
	changeStatus('C_AWAY')
}

function logoutUser(){
	if (userAwayTimeoutId != null && userSessionExpireTimeoutId != null){
		clearInterval(userAwayTimeoutId);
		clearInterval(userSessionExpireTimeoutId);
	}
	
	// no more receiving
	if (onlineUserTimeoutId != null && messageReceiveTimoutId != null){
		clearInterval(onlineUserTimeoutId);
		clearInterval(messageReceiveTimoutId);
	}
	
	changeStatus('D_LOGOUT')

	if (dijit.byId("logoutDialog") == null){
		
		myDialog = new dijit.Dialog({
			  id:'logoutDialog',
		      title: "Session Timeout",
		      content: "You are inactive for long time. <br>" +
		      		" Do you want to logout? <br> Click <b>'Yes'</b> to logout Or Click <b>'No'</b> to stay connected  <br> <br>" +
		      		" <button dojoType='dijit.form.Button' type='button' onclick=doActualLogout() >Yes</button>&nbsp;" +
		      		" <button dojoType='dijit.form.Button' type='button' onclick='cancelLogout()'>No</button>",
		      style: "width: 400px"
		  });
	}
	dijit.byId("logoutDialog").show()

	
}

function doActualLogout(){
	window.location =logoutURL;
}
function cancelLogout(){
	getOnlineUsersFrmServer();
	receiveMessagesFrmServer();
	resetSessionTimers()
	changeStatus('A_AVAILABLE');
	dijit.byId("logoutDialog").hide()
}

